package com.example.demo.controller;

import com.example.demo.bean.*;
import com.example.demo.service.CommentService;
import com.example.demo.service.IndentService;
import com.example.demo.service.InformationService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by yanmaoyuan on 2018/4/16.
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private InformationService informationService;

//    @Autowired
//    private IndentService indentService;
//
//    @Autowired
//    private CommentService commentService;

    //登录验证
    @PostMapping(value = "/login")
    public HashMap<String, Object> login(@RequestParam(value = "studentId") String studentId, @RequestParam(value = "password") String password) {
        HashMap<String, Object> hashMap = new HashMap<>();
        boolean flag = false;
        User user = userService.getUserByStudentId(studentId);
        String pass = user.getPassword();
        if(password.equals(pass)){
            flag = true;
        }else{
        }
        hashMap.put("status", "success");
        hashMap.put("loginStatus", flag);
        return hashMap;
    }

    //新增用户
    @PostMapping(value = "/add")
    public HashMap<String, Object> addUser(@RequestParam(value = "userName") String userName,@RequestParam(value = "gender") String gender,@RequestParam(value = "studentId") String studentId,
                                           @RequestParam(value = "department") String department,@RequestParam(value = "major") String major,
                                           @RequestParam(value = "phoneNum") String phoneNum, @RequestParam(value = "password") String password, @RequestParam(value = "avatar") String avatar) {
        HashMap<String, Object> hashMap = new HashMap<>();
        User user=new User(userName,gender,studentId,password,department,major,phoneNum,avatar,"user");
        if(user != null){
            hashMap.put("status", "success");
            userService.addUser(user);
            hashMap.put("userId", user.getUserId());
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //更新用户信息
    @PostMapping(value = "/modify")
    public void modifyUser(@RequestParam(value = "userId") String userId,@RequestParam(value = "userName") String userName,@RequestParam(value = "gender") String gender,
                           @RequestParam(value = "department") String department,@RequestParam(value = "major") String major,@RequestParam(value = "password") String password,
                           @RequestParam(value = "phoneNum") String phoneNum,@RequestParam(value = "studentId") String studentId,@RequestParam(value = "avatar") String avatar) {
        User user=userService.getUserById(userId);
        user.setUserName(userName);
        user.setGender(gender);
        user.setDepartment(department);
        user.setMajor(major);
        user.setPassword(password);
        user.setPhoneNum(phoneNum);
        user.setStudentId(studentId);
        user.setAvatar(avatar);
        userService.save(user);
    }

    //根据userId获取一个用户对象
    @GetMapping(value = "/getOne")
    public HashMap<String, Object> findUser(@RequestParam(value = "userId") String userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        User user = userService.getUserById(userId);
        if(user != null){
            hashMap.put("status", "success");
            hashMap.put("user", user);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

//    //根据wechatId获取一个用户对象
//    @GetMapping(value = "/getByWechat")
//    public HashMap<String, Object> getUserByWechat(@RequestParam(value = "wechatId") String wechatId) {
//        HashMap<String, Object> hashMap = new HashMap<>();
//        User user = userService.getUserByWechat(wechatId);
//        if(user != null){
//            hashMap.put("status", "success");
//            hashMap.put("user", user);
//        }else{
//            hashMap.put("status", "failure");
//        }
//        return hashMap;
//    }

    //根据studentId获取一个用户对象
    @GetMapping(value = "/getByStudentId")
    public HashMap<String, Object> getUserByStudentId(@RequestParam(value = "studentId") String studentId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        User user = userService.getUserByStudentId(studentId);
        if(user != null){
            hashMap.put("status", "success");
            hashMap.put("user", user);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //根据userId获取用户的收藏列表
    @GetMapping(value = "/getInfoList")
    public HashMap<String, Object> getInfoList(@RequestParam(value = "userId") String userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        User user = userService.getUserById(userId);
        if(user.getCollects() != null){
            hashMap.put("status", "success");
            hashMap.put("infoList", user.getCollects());
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //添加收藏
    @PostMapping(value = "/addCollect")
    public void addCollect(@RequestParam(value = "userId") String userId,@RequestParam(value = "informationId") String informationId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        User user = userService.getUserById(userId);
        Information information = informationService.getInformationById(informationId);
        List<Information> infos = user.getCollects();
        infos.add(information);
        user.setCollects(infos);
        userService.addUser(user);
    }

    //删除收藏
    @PostMapping(value = "/removeCollect")
    public void removeCollect(@RequestParam(value = "userId") String userId,@RequestParam(value = "informationId") String informationId) {
        User user = userService.getUserById(userId);
        Information information = informationService.getInformationById(informationId);
        List<Information> infos = user.getCollects();
        infos.remove(information);
        user.setCollects(infos);
        userService.addUser(user);
    }

//    //获取用户好评率
//    @GetMapping(value = "/getRate")
//    public HashMap<String, Object> getRate(@RequestParam(value = "userId") String userId) {
//        HashMap<String, Object> hashMap = new HashMap<>();
//        List<Indent> indents = indentService.getIndentByUserAndStatus(userId, "已完成");
//        int total = indents.size();
//        List<Comment> comments = commentService.getGoodComment(userId);
//        int good = comments.size();
//        double rate = 0.0;
//        int rateInt = 0;
//        if(total != 0){
//            rate = ((double)good/(double)total) * 100;
//            rateInt = (int) rate;
//        }else{
//        }
//        if(indents != null && comments != null){
//            hashMap.put("status", "success");
//            hashMap.put("rate", rateInt);
//        }else{
//            hashMap.put("status", "failure");
//        }
//        return hashMap;
//    }

    //根据userId获取用户收藏列表
    @GetMapping(value = "/getCollections")
    public HashMap<String, Object> getAllCollections(@RequestParam(value = "userId") String userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        List<HashMap<String, Object>> list = new ArrayList<>();
        User user = userService.getUserById(userId);
        List<Information> collects = user.getCollects();
        for(Information collect : collects){
            HashMap<String, Object> map1 = new HashMap<>();
            User user1 = userService.getUserById(collect.getUserId());
            map1.put("user", user1);
            map1.put("information", collect);
            map1.put("isMyCollection", 1);
            list.add(map1);
        }
        if(list != null){
            hashMap.put("status", "success");
            hashMap.put("collections", list);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //上传用户头像
    @RequestMapping(value = "/upload", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String upload(@RequestParam(value = "userId") String userId, HttpServletRequest request) throws IOException{
        MultipartHttpServletRequest req=(MultipartHttpServletRequest)request;
        MultipartFile file=req.getFile("file");
        if (file.isEmpty()) {
            return "所选图像文件为空";
        }
        // 获取文件名
        String fileName = userId+file.getOriginalFilename();
        //获取文件大小
        int size=(int)file.getSize();
        System.out.println(fileName+"-->"+size);
        // 获取文件的后缀名
        // String suffixName = fileName.substring(fileName.lastIndexOf("."));
        File directory=new File("");
//        // 文件上传后的路径
//        String filePath = directory.getCanonicalPath();

//        String rootPath = System.getProperty("user.dir");

        File dest = new File("/home/file/user/"+ fileName);
//        File dest = new File("/home/file/information/"+ fileName);
        try {
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            System.out.println("上传成功");
//            return "/home/file/"+ fileName;
            return "http://120.77.247.244:8080/user/" + fileName;
//            return "http://120.77.247.244:8080/user/" + fileName;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

}